package com.zheng.oauthapi.component;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.zheng.oauthapi.domain.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginUserHolder {
    public UserDto getCurrentUser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = requestAttributes.getRequest();
        String header = req.getHeader("user");
        JSONObject user = new JSONObject(header);
        UserDto dto = new UserDto();
        dto.setUsername(user.getStr("user_name"));
        dto.setId(Convert.toLong(user.get("id")));
        dto.setRoles(Convert.toList(String.class, user.get("authorities")));
        return dto;
    }
}
